import Field from '@model/entity/Field';
import ExecuteCodeClass from '@src/component/form/components/FormJsControl/model/executeCode';

/* 校验代码中不能有的特殊字段 */
export function checkJsCode(code: string) {
  // 要校验的特殊字段
  const FITER_SPECIAL_FIELDS = ['eval', 'setTimeout', 'setInterval', 'alert', 'debugger'];
  // 构建正则表达式
  const regex = new RegExp(FITER_SPECIAL_FIELDS.join('|'), 'gi');
  // 校验代码
  const isForbidden = regex.test(code);
  return isForbidden;
}

/* 解析js代码块 */
export async function executeCode(code: string, form: any, field: Field, forceUpdate: boolean = false, config: any = {}) {
  const executeCodeClassInstance =  ExecuteCodeClass.getInstance({...config});
  return await executeCodeClassInstance.executeCode(code, form, field, forceUpdate, config);
}
/* 判断字符串是否是对象能解析成对象 */
export function isObjectString(str: string) {
  try {
    var obj = JSON.parse(str);
    return typeof obj === 'object' && obj !== null;
  } catch (error) {
    return false;
  }
}
/* 判断字符串是否是对象能解析成对象 */
export function syntaxHighlight(jsonString: string) {
  jsonString = JSON.stringify(JSON.parse(jsonString), null, 2);
  const formattedJson = jsonString
    .replace(/&/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>');
  return formattedJson.replace(
    /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
    function(match) {
      var cls = 'number';
      if (/^"/.test(match)) {
        if (/:$/.test(match)) {
          cls = 'key';
        } else {
          cls = 'string';
        }
      } else if (/true|false/.test(match)) {
        cls = 'boolean';
      } else if (/null/.test(match)) {
        cls = 'null';
      }
      return '<span class="' + cls + '">' + match + '</span>';
    }
  );
}
/**
 * 匹配与代码块进行关联的表单
 * @param {*} field - 当前字段
 * @param {*} fields - 所有表单字段
 */
export function matchFormField(field: Field,fields: Field[]) {
  const { fieldName } = field;
  return fields.filter((f: Field) => {
    const {dataSourceType, relatedCodeTemplate = {}} = f.setting || {};
    return dataSourceType == 3 && (relatedCodeTemplate?.aliasFieldName == fieldName);
  });
}

export default {
  executeCode,
  isObjectString,
  syntaxHighlight,
  checkJsCode,
  matchFormField,
};
